<!-- 新增和编辑弹窗 -->
<template>
  <a-modal
    :width='800'
    :visible='visible'
    :confirm-loading='loading'
    :title="isUpdate ? '修改作业规则' : '新建作业规则'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible='updateVisible'
    @ok='save'
  >
    <a-form
      layout='horizontal'
      ref='form'
      :model='form'
      :label-col='{ md: { span: 6 }, sm: { span: 24 } }'
      :wrapper-col='{ md: { span: 18 }, sm: { span: 24 } }'
    >
      <a-form-item label='作业模式:' name='workMode'>
        <a-select v-model:value="form.workMode">
          <a-select-option :value="1">按次数</a-select-option>
          <a-select-option :value="2">固定时间间隔</a-select-option>
          <a-select-option :value="3">自定义</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item v-if="form.workMode == 1 || form.workMode == 2" label='每天作业次数:' name='dayWorkNum'>
        <a-input-number v-model:value='form.dayWorkNum' style="width:300px" placeholder='请输入每天作业几次' allow-clear autocomplete='off' />
      </a-form-item>
      <a-form-item v-if="form.workMode == 1 || form.workMode == 2" label='作业起始时分,如08:00:' name='dayWorkStart'>
        <a-time-picker v-model:value='form.dayWorkStart' format="HH:mm" valueFormat="HH:mm" placeholder='请输入时分,如08:00' allow-clear autocomplete='off' />
      </a-form-item>
      <a-form-item v-if="form.workMode == 1" label='作业结束时分,如08:00:' name='dayWorkEnd'>
        <a-time-picker v-model:value='form.dayWorkEnd' format="HH:mm" valueFormat="HH:mm" placeholder='请输入时分,如08:00' allow-clear autocomplete='off' />
      </a-form-item>
      <a-form-item v-if="form.workMode == 2" label='每次作业时长(秒):' name='workTimes'>
        <a-input-number v-model:value='form.workTimes' style="width:300px" placeholder='请输入每次作业多久，秒' allow-clear autocomplete='off' />
      </a-form-item>
      <a-form-item v-if="form.workMode == 2" label='每次作业冗余时长(秒):' name='workRedundance'>
        <a-input-number v-model:value='form.workRedundance' style="width:300px" placeholder='请输入每次作业冗余多久，秒' allow-clear autocomplete='off' />
      </a-form-item>
      <a-form-item v-if="form.workMode == 2" label='每次作业间隔时长(秒):' name='workInterval'>
        <a-input-number v-model:value='form.workInterval' style="width:300px" placeholder='请输入每次作业间隔多久，秒' allow-clear autocomplete='off' />
      </a-form-item>

      <div style="margin-left: 120px;margin-top: 25px;" v-if="form.workMode == 3">
        <VehicleManagerVehicleUsemodelWorkruleEditSub v-for="(item, index) in timeRangeItems"
                                              :key="index" :index="index" :timeRange="item" @deleteIndex="removeTimeRange"
        />

        <a-button type='primary' html-type='button' @click="addTimeRange">
          新增时间段
        </a-button>
      </div>

      <a-divider />
      <a-button v-if="isDelete" style="margin-left: 120px;margin-top: 25px;" type='primary' html-type='button' @click="clearConfig">
        清除规则
      </a-button>
    </a-form>
  </a-modal>
</template>

<script>
import {VehicleWorkRuleModeApi} from "@/api/property/vechile/VehicleWorkRuleModeApi";
import { message } from 'ant-design-vue';
import VehicleManagerVehicleUsemodelWorkruleEditSub from './vehicle-usemodel-workrule-edit-sub.vue'

export default {
  name: 'VehicleManagerVehicleUsemodelWorkruleEdit',
  components: {
    VehicleManagerVehicleUsemodelWorkruleEditSub
  },
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  created(){
    let that = this;
    if (this.data) {
      let detailPromise = VehicleWorkRuleModeApi.detailByMode(this.data.id);
      detailPromise.then(function(result){
        if (result && result.vwrmId) {
          that.form = result;
          that.isUpdate = true;
          that.isDelete = true;
          if (result.dayWorkTimeRange) {
            that.timeRangeItems = JSON.parse(result.dayWorkTimeRange);
            console.log(that.timeRangeItems);
          }
        } else {
          that.form = {};
          that.form.workMode = 2;
          that.isUpdate = false;
          that.isDelete = false;
        }
      }).catch((err) => {
        message.error(err);
        console.log(err);
      });
    } else {
      this.form = {};
      that.form.workMode = 2;
      this.isUpdate = false;
      that.isDelete = false;
    }
  },
  data() {
    return {
      // 表单数据
      form: Object.assign({}, this.data),
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
      isDelete : false,
      timeRangeItems : []
    };
  },
  methods: {
    /**
     * 保存和编辑
     *
     * @author cancan
     * @date 2024/01/18 23:19
     */
    async save() {
      console.log(this.form);
      this.form.modeId = this.data.id;
      // 校验表单
      if (this.form.workMode == 1) {
        if (this.form.dayWorkStart == '' || this.form.dayWorkEnd == '') {
          message.error("请完善起始时间和结束时间");
          return false;
        }
        let currentDate = new Date();
        let startTimeS = this.form.dayWorkStart.split(":");
        let endTimeS = this.form.dayWorkEnd.split(":");
        if (currentDate.setHours(startTimeS[0], startTimeS[1]) > currentDate.setHours(endTimeS [0], endTimeS [1])) {
          message.error("起始时间应该小于结束时间");
          return false;
        }
      } else if (this.form.workMode == 3) {
        if (this.timeRangeItems == null || this.timeRangeItems.length == 0) {
          message.error("请增加时间段");
          return false;
        }
        for (let i = 0; i < this.timeRangeItems.length; i ++ ) {
          //当前自己比
          if (this.timeRangeItems[i].start == null || this.timeRangeItems[i].start == ''
            || this.timeRangeItems[i].end == null || this.timeRangeItems[i].end == ''
          ) {
            message.error("请完善时间段" + (i+1));
            return false;
          }
          let currentDate1 = new Date();
          let startTimeS1 = this.timeRangeItems[i].start.split(":");
          let endTimeS1 = this.timeRangeItems[i].end.split(":");
          if (currentDate1.setHours(startTimeS1[0], startTimeS1[1]) > currentDate1.setHours(endTimeS1 [0], endTimeS1 [1])) {
            message.error("时间段"+ (i+1) + "起始时间应该小于结束时间");
            return false;
          }
          if (i < this.timeRangeItems.length - 1) { //已经是最后一个了，就不和下一个比了
            if (this.timeRangeItems[i + 1].start == null || this.timeRangeItems[i + 1].start == ''
              || this.timeRangeItems[i + 1].end == null || this.timeRangeItems[i + 1].end == ''
            ) {
              message.error("请完善时间段" + (i+2));
              return false;
            }
            let currentDate2 = new Date();
            let startTimeS2 = this.timeRangeItems[i].end.split(":");
            let endTimeS2 = this.timeRangeItems[i+1].start.split(":");
            if (currentDate2.setHours(startTimeS2[0], startTimeS2[1]) > currentDate2.setHours(endTimeS2 [0], endTimeS2 [1])) {
              message.error("时间段"+ (i+1) + "结束时间应该小于时间段" + (i+2) + "开始时间");
              return false;
            }
          }
        }
        this.form.dayWorkTimeRange = JSON.stringify(this.timeRangeItems);
      }
      // 修改加载框为正在加载
      this.loading = true;

      let result = null;

      // 执行编辑或修改
      if (this.isUpdate) {
        result = VehicleWorkRuleModeApi.edit(this.form);
      } else {
        result = VehicleWorkRuleModeApi.add(this.form);
      }
      result
        .then(result => {
          // 移除加载框
          this.loading = false;

          // 提示添加成功
          message.success(result.message);

          // 如果是新增，则form表单置空
          if (!this.isUpdate) {
            this.form = {};
          }

          // 关闭弹框，通过控制visible的值，传递给父组件
          this.updateVisible(false);

          // 触发父组件done事件
          this.$emit('done');
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /**
     * 更新编辑界面的弹框是否显示
     *
     * @param value true-显示，false-隐藏
     * @author cancan
     * @date 2024/01/18 23:19
     */
    updateVisible(value) {
      this.$emit('update:visible', value);
    },
    async clearConfig(){
      if (this.form.vwrmId > 0) {
        const result = await VehicleWorkRuleModeApi.delete({ vwrmId: this.form.vwrmId });
        message.success(result.message);
        this.updateVisible(false);

        // 触发父组件done事件
        this.$emit('done');
      }
    },
    addTimeRange() {
      this.timeRangeItems.push({});
    },
    removeTimeRange(index) {
      if (index !== 0) {
        this.timeRangeItems.splice(index, 1)
      }
    }
  }
};
</script>
